package com.qujia.station.service.impl;

import com.qujia.common.core.domain.entity.SysUser;
import com.qujia.common.exception.CustomException;
import com.qujia.common.utils.SecurityUtils;
import com.qujia.common.utils.StringUtils;
import com.qujia.station.domain.WxMessageTemplate;
import com.qujia.station.domain.form.WxMessageTemplateForm;
import com.qujia.station.domain.form.WxMessageTemplateQueryForm;
import com.qujia.station.domain.vo.WxMessageTemplateQueryVo;
import com.qujia.station.domain.vo.WxMessageTemplateVo;
import com.qujia.station.mapper.WxMessageTemplateMapper;
import com.qujia.station.service.WxMessageTemplateService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
public class WxMessageTemplateServiceImpl implements WxMessageTemplateService {

    @Autowired
    private WxMessageTemplateMapper wxMessageTemplateMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertWxMessageTemplate(WxMessageTemplateForm wxMessageTemplateForm) {
        operaPermission(wxMessageTemplateForm.getEnterpriseId());

        wxMessageTemplateForm.getWxTemplateContentList().forEach(wxTemplateContent -> {
            WxMessageTemplate wxMessageTemplate = new WxMessageTemplate();
            if (StringUtils.isEmpty(wxTemplateContent.getTemplateId())) throw new CustomException("模板id不能为空");
            if (ObjectUtils.isEmpty(wxTemplateContent.getTemplateType())) throw new CustomException("模板类型不能为空");

            BeanUtils.copyProperties(wxTemplateContent, wxMessageTemplate);
            wxMessageTemplate.setEnterpriseId(wxMessageTemplateForm.getEnterpriseId());
            wxMessageTemplate.setPushChannel(wxMessageTemplateForm.getPushChannel());
            wxMessageTemplate.setCreatedBy(SecurityUtils.getUsername());
            wxMessageTemplate.setUpdatedBy(SecurityUtils.getUsername());
            try {
                wxMessageTemplateMapper.insertWxMessageTemplate(wxMessageTemplate);
            } catch (DuplicateKeyException duplicateKeyException) {
                throw new CustomException("该油企已存在记录！");
            }
        });
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateWxMessageTemplate(WxMessageTemplateForm wxMessageTemplateForm) {
        operaPermission(wxMessageTemplateForm.getEnterpriseId());

        for (WxMessageTemplateForm.WxTemplateContent wxTemplateContent : wxMessageTemplateForm.getWxTemplateContentList()) {
            if (ObjectUtils.isEmpty(wxTemplateContent.getId())) {
                WxMessageTemplate result = wxMessageTemplateMapper.getByEnterpriseIdAndType(wxMessageTemplateForm.getEnterpriseId(), wxTemplateContent.getTemplateType());
                if (ObjectUtils.isNotEmpty(result)) throw new CustomException("模板id不能为空");

                WxMessageTemplate wxMessageTemplate = new WxMessageTemplate();
                BeanUtils.copyProperties(wxTemplateContent, wxMessageTemplate);
                wxMessageTemplate.setEnterpriseId(wxMessageTemplateForm.getEnterpriseId());
                wxMessageTemplate.setPushChannel(wxMessageTemplateForm.getPushChannel());
                wxMessageTemplate.setCreatedBy(SecurityUtils.getUsername());
                wxMessageTemplate.setUpdatedBy(SecurityUtils.getUsername());
                wxMessageTemplateMapper.insertWxMessageTemplate(wxMessageTemplate);
                continue;
            }

            WxMessageTemplate wxMessageTemplate = new WxMessageTemplate();
            BeanUtils.copyProperties(wxTemplateContent, wxMessageTemplate);
            wxMessageTemplate.setEnterpriseId(wxMessageTemplateForm.getEnterpriseId());
            wxMessageTemplate.setPushChannel(wxMessageTemplateForm.getPushChannel());
            wxMessageTemplate.setUpdatedBy(SecurityUtils.getUsername());
            wxMessageTemplate.setUpdatedTime(new Date());
            try {
                wxMessageTemplateMapper.updateWxMessageTemplate(wxMessageTemplate);
            } catch (DuplicateKeyException duplicateKeyException) {
                throw new CustomException("该油企已存在记录！");
            }
        }
    }

    @Override
    public WxMessageTemplateVo selectWxMessageTemplateById(Long enterpriseId) {
        return wxMessageTemplateMapper.getByEnterpriseId(enterpriseId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteWxMessageTemplate(String enterpriseIds) {
        List<String> enterpriseIdList = Arrays.asList(enterpriseIds.split(","));
        enterpriseIdList.forEach(enterpriseId -> {
            operaPermission(Long.valueOf(enterpriseId));
            WxMessageTemplateVo wxMessageTemplateVo = wxMessageTemplateMapper.getByEnterpriseId(Long.valueOf(enterpriseId));
            if(ObjectUtils.isEmpty(wxMessageTemplateVo) || ObjectUtils.isEmpty(wxMessageTemplateVo.getWxTemplateContentList())) return;

            wxMessageTemplateVo.getWxTemplateContentList().forEach(wxTemplateContentVo -> {
                WxMessageTemplate wxMessageTemplate = new WxMessageTemplate();
                wxMessageTemplate.setId(wxTemplateContentVo.getId());
                wxMessageTemplate.setUpdatedBy(SecurityUtils.getUsername());
                wxMessageTemplate.setUpdatedTime(new Date());
                wxMessageTemplate.setDel(System.currentTimeMillis());
                wxMessageTemplateMapper.updateWxMessageTemplate(wxMessageTemplate);
            });
        });
    }

    @Override
    public List<WxMessageTemplateQueryVo> pageWxMessageTemplate(WxMessageTemplateQueryForm queryForm) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        String userLevel = user.getUserLevel();
        if (StringUtils.isNotEmpty(userLevel) && ObjectUtils.notEqual(userLevel, "0")) {
            queryForm.setEnterpriseId(user.getEnterpriseId());
        }

        return wxMessageTemplateMapper.pageWxMessageTemplate(queryForm);
    }

    /**
     * 判断当前登录用户是否拥有操作权限
     * @param enterpriseId 油企id
     */
    private void operaPermission(Long enterpriseId) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        String userLevel = user.getUserLevel();
        if (StringUtils.isNotEmpty(userLevel) && userLevel.equals("0"))
            throw new CustomException("没有权限操作微信模板，请使用油企账号操作！");
        if (StringUtils.isNotEmpty(userLevel) && userLevel.equals("1") && ObjectUtils.notEqual(user.getEnterpriseId(), enterpriseId)) // 1:油企
            throw new CustomException("没有权限操作！");
        if (StringUtils.isNotEmpty(userLevel) && userLevel.equals("2")) // 2:油站
            throw new CustomException("没有权限操作微信模板，请使用油企账号操作！");
    }
}
